<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	
	class Login extends Admin_Controller{

		public function __construct(){
			parent::__construct();
			$this->load->model('database_model');
		}

		public function index(){
			if(!is_user_logged_in()){
				$data = array(
					'header' => 'Login'
					);
				$this->load->view('admin/login', $data);
			}else{
				redirect('admin/dashboard', 'refresh');
			}
			
		}

		public function checklogin(){
			if(!serverReferer()){
				redirect('admin/login', 'refresh');
			}
	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[30]|xss_clean');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|max_length[30]|xss_clean');

			if($this->form_validation->run() === FALSE){
				$json = array(
					'status' => '0', 
					'message' => validation_errors()
					);
				echo json_encode($json);
			}else{
				$username = $this->input->post('username', TRUE);
				$password = $this->input->post('password', TRUE);
				$data = array(
					'Username' =>$username,
					'Password' => do_hash($password,'md5')
					);
				$result = $this->database_model->GetWhere('ci_users', $data);
				if($result->num_rows()>0){
					$r = $result->row();
					$userdata = array(
						'userid' => $r->ID,
						'username' => $username,
						'is_user_logged' => 1
						);
					$this->session->set_userdata($userdata);
					$json = array(
						'status' => '1',
						'message' => 'Successful. Redirecting to dashboard'
						);
					echo json_encode($json);
				}else{
					$json = array(
						'status' => '0',
						'message' => 'Username or Password is incorrect'
						);
					echo json_encode($json);
				}
			}
		}
	}
?>